# coding=utf-8
"""
作者：董新强 
创建时间：
描述：
"""
from tornado.gen import coroutine

from base_handler import BaseHandler
from framework.msg import failure
from framework.redis_helper import ReidsHelper
from framework.utilities import to_string, to_list
from pools import run_async
from services.cat_service.ability_manage import AbilityManage
from services.cat_service.cat_manage import CatManage
from services.cat_service.error_manage import ErrorManage
from services.cat_service.report_manage import ReportManage


class AnswerHandler(BaseHandler):
    ''''
    答题
    '''

    def cache_key(self, aid):
        return 'aws_%d_%d' % (self.uid, aid)

    @coroutine
    def get_pre_answers(self, cache, aid):
        answers = yield cache.get(self.cache_key(aid))
        return to_list(answers)

    @coroutine
    def update_ansers(self, cache, aid, answer_info_ls):
        yield cache.set(self.cache_key(aid), to_string(answer_info_ls))

    @coroutine
    def delete_answers(self, cache, aid):
        yield cache.delete(self.cache_key(aid))

    @coroutine
    def post(self):
        """答题"""
        if not self.validated:
            return self.finish(failure(msg='没有权限').responseMsg())

        qid = self.req_dict('qid', int)
        aid = self.req_dict('aid', int)
        answer = self.req_dict('answer')
        if not aid or not qid or not answer:
            return BaseHandler.to_reponse(self, failure(msg='参数错误'))

        cache = ReidsHelper()  # 初始化缓存
        result = None
        try:
            pre_answers = yield self.get_pre_answers(cache, aid=aid)  # 从缓存中获取答案

            # 答题
            inst = CatManage(usr=self.usr, ability_id=aid, selector='difficult', pre_answers=pre_answers)
            result = yield run_async(inst.to_answer, qid, answer)

            if result.is_ok():
                if 'answers' in result.data:  # 更新缓存
                    yield self.update_ansers(cache, aid=aid, answer_info_ls=result.data.pop('answers'))
                elif 'finished' in result.data:
                    yield self.delete_answers(cache, aid=aid)

        except Exception as e:
            print('to_answer.post=>', e)
        finally:
            cache.close()

        BaseHandler.to_reponse(self, result)


class QuestionHandler(BaseHandler):
    '''
    获取答题
    '''

    def http_post(self):
        aid = self.req_dict('aid', int)
        if not aid:
            return failure(msg='参数错误')

        inst = CatManage(usr=self.usr, ability_id=aid)
        result = inst.start_test()
        return result


class AbilityHandler(BaseHandler):
    def http_get(self):
        inst = AbilityManage(self.usr)
        pid = self.req_dict('id', int)
        if pid:
            return inst.get_child_abilities(pid)
        return inst.get_ability_list()


class ReportScoreHandler(BaseHandler):
    def http_get(self):
        return ReportManage(self.usr).get_report(self.req_dict('id', int))


class AbilityPublicHandler(BaseHandler):
    def http_get(self):
        inst = AbilityManage(self.usr)
        return inst.get_ability_list()


class ErrorAnswerHandler(BaseHandler):
    def http_get(self):
        inst = ErrorManage(self.usr)
        return inst.get_error_ls(self.req_dict('id', int))
